package com.best.oasis.settlement.service.security;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.best.oasis.settlement.common.entity.security.RoleGroup;
import com.best.oasis.settlement.common.entity.security.RoleGroupMapping;
import com.best.oasis.settlement.common.so.security.RoleGroupSO;
import com.best.oasis.settlement.common.vo.security.RoleGroupVO;
import com.best.oasis.settlement.common.vo.security.RoleVO;
import com.best.oasis.settlement.common.vo.security.UserVO;
import com.best.oasis.settlement.dao.security.RoleDao;
import com.best.oasis.settlement.dao.security.RoleGroupDao;
import com.best.oasis.settlement.service.base.BaseServiceImpl;
import com.best.oasis.settlement.service.base.BusinessException;
import com.best.oasis.settlement.util.page.PageList;


@Service
public class RoleGroupServiceImpl extends BaseServiceImpl<RoleGroup, RoleGroupVO, Long> implements RoleGroupService {
	@Autowired
    private RoleGroupDao roleGroupDao;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService; 
	@Autowired
	private RoleDao roleDao;
    @Override
    public void afterConstruct() {
        super.setBaseDao(roleGroupDao);
        super.setEntityClass(RoleGroup.class);
        super.setEntityVOClass(RoleGroupVO.class);

    }
	@Override
	public void remove(Long id) {
		List<UserVO> userList;
		RoleGroupVO vo = this.get(id);
		userList=userService.getUsersByRoleGroupId(id);
		if(userList!=null && userList.size()>0){
			throw new RuntimeException("用户组["+vo.getName()+"]中用户数目不为空，不能删除！");
		}
		
		roleDao.removeRoleGroupRole(id);

		super.remove(id);
	}
	@Override
	public void remove(List<Long> ids){
	    for(Long id:ids){
	        remove(id);
	    }
	}
	@SuppressWarnings("unchecked")
	@Override
	public PageList<RoleGroupVO> getRoleGroupPageList(RoleGroupSO so) {
    	PageList<RoleGroupVO> result = new PageList<RoleGroupVO>();
    	result = orikaBeanMapper.convertPageList(roleGroupDao.getPageList(so), entityVOClass);
    	for(RoleGroupVO vo:result.getList()){
    	    vo.setRoles(roleService.getRolesByRoleGroupId(vo.getId()));
    	}
    	return result;

	}
	/**
	 * 授予某个用户一组RoleGroup权限
	 * @param user 被授权的用户
	 * @param roleGroupIds
	 */
	@Override
	public void authorize(UserVO user, List<Long> roleGroupIds) {
	    List<RoleGroupVO> newRoleGroups = new ArrayList<RoleGroupVO>();
		 
		
		if(roleGroupIds!=null){
			newRoleGroups = this.getAll(roleGroupIds);
		}	
		user.setRoleGroups(newRoleGroups);
		userService.save(user);		
	}
	/**
	 * 根据一组roleGroupId,获取所有RoleGroup
	 */
	@Override
	public List<RoleGroupVO> getAll(List<Long> roleGroupIds) {
		List<Long> ids = new ArrayList<Long>(roleGroupIds); 
		List<RoleGroupVO> roleGroupList = new ArrayList<RoleGroupVO>();
		for (Long id : ids) {
			RoleGroupVO vo = get(id);
			roleGroupList.add(vo);
		}
		
		List<RoleGroupVO> set2 = new ArrayList<RoleGroupVO>(roleGroupList);
		return set2;
	}
	/**
	 * 根据一组roleGroupId,获取所有Role
	 */
	@Override
	public List<RoleVO> getAllRoles(List<Long> roleGroupIds) {
	    List<RoleVO> roles;
        Set<RoleVO> roleSet = new HashSet<RoleVO>();
        if(roleGroupIds!=null && roleGroupIds.size()>0){
            for(Long id:roleGroupIds){
                roleSet.addAll(roleService.getRolesByRoleGroupId(id));
            }
        }
        roles = new ArrayList<RoleVO>(roleSet);
        return roles;
	}
	
	public RoleGroupVO get(Long id) {
		RoleGroupVO result = super.get(id);
		result.setRoles(roleService.getRolesByRoleGroupId(result.getId()));
		return result;
	}
	
	/**
	 * 修改某一个roleGroup
	 * @param roleGroup
	 * @param roles 该roleGroup拥有的所有Role
	 */
	@Override
	public RoleGroupVO update(RoleGroupVO roleGroup) {
		List<RoleVO> newRoles = new ArrayList<RoleVO>();
//		RoleGroupSO so = new RoleGroupSO();
//		so.setName(roleGroup.getName());
//		so.setId(roleGroup.getId());
		//List<RoleGroupVO> vos = getAllByName(so);
		List<RoleGroupVO> vos = getListBy("name", roleGroup.getName()) ;
		if (vos != null && vos.size() > 0) {
			for (RoleGroupVO item : vos) {
				if ( !item.getId().equals( roleGroup.getId() ) ) {
					throw new BusinessException("", "角色名已存在!");
				}
			}
		}
		List<RoleVO> roles = roleGroup.getRoles();
		if (roles != null) {
			for (RoleVO r : roles) {
				RoleVO role = roleService.get(r.getId());
				if (role != null) {
					newRoles.add(role);
				}
			}
		}
		roleGroup = super.update(roleGroup);
		// 更改拥有该roleGroup的所有users的权限
		List<UserVO> users = userService.getUsersByRoleGroupId(roleGroup.getId());

		// 根据groupId删除CRM_USER_ROLE的记录
		userService.removeUserRoleByRoleGroupId(roleGroup.getId());

		// 维护ROLEGROUP_ROLE的关系,先全部删了....再添加新的....
		roleDao.removeRoleGroupRole(roleGroup.getId());

		RoleGroupMapping roleGroupRole;
		for (RoleVO role : newRoles) {
			roleGroupRole = new RoleGroupMapping();
			roleGroupRole.setRole_Id(role.getId());
			roleGroupRole.setRolegroup_Id(roleGroup.getId());
			roleDao.createRoleGroupRole(roleGroupRole);
		}

		roleGroup = get(roleGroup.getId());

		if (users != null && users.size() > 0) {
			List<RoleGroupVO> groups = null;
			for (UserVO user : users) {
				groups = new ArrayList<RoleGroupVO>();
				if (user.getRoleGroups() != null && user.getRoleGroups().size() > 0) {
					for (RoleGroupVO item : user.getRoleGroups()) {
						if (item.getId() != roleGroup.getId()) {
							groups.add(item);
						}
					}
				}
				groups.add(roleGroup);
				user.setRoleGroups(groups);
				userService.update(user);
			}
		}
		return roleGroup;
		
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public RoleGroupVO getByRoleName(String roleName) {
		RoleGroupSO so = new RoleGroupSO();
		so.setName(roleName);
		RoleGroupVO result = (RoleGroupVO)orikaBeanMapper.convert(roleGroupDao.getBy("name", roleName), entityVOClass);
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<RoleGroupVO> getAllByName(RoleGroupSO so) {
		List<RoleGroupVO> result = (List<RoleGroupVO>)orikaBeanMapper.convertList(roleGroupDao.getAllByName(so), entityVOClass);
		for(RoleGroupVO vo:result){
    	    vo.setRoles(roleService.getRolesByRoleGroupId(vo.getId()));
    	}
		return result;
	}
	@SuppressWarnings("unchecked")
    @Override
    public List<RoleGroupVO> getRoleGroupsByUserid(Long userID) {
        List<RoleGroupVO> roleGroups = (List<RoleGroupVO>)orikaBeanMapper.convertList(roleGroupDao.getRoleGroupsByUserid(userID), entityVOClass);
        return roleGroups;
    }
	@SuppressWarnings("unchecked")
    @Override
    public List<RoleGroupVO> getAll(){
	    List<RoleGroupVO> result = new ArrayList<RoleGroupVO>();
        result = (List<RoleGroupVO>)orikaBeanMapper.convertList(roleGroupDao.getAll(), entityVOClass);
        for(RoleGroupVO vo:result){
            vo.setRoles(roleService.getRolesByRoleGroupId(vo.getId()));
            vo.setUsers(userService.getUsersByRoleGroupId(vo.getId()));
        }
        return result;
	}
	/**
	 * 获得所有的RoleGroup对象，且该对象所关联的roles和users不会被级联取出
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<RoleGroupVO> getAllWithoutCascade(){
		 List<RoleGroupVO> result = new ArrayList<RoleGroupVO>();
	     result = (List<RoleGroupVO>)orikaBeanMapper.convertList(roleGroupDao.getAll(), entityVOClass);
	     return result;		
	}
    @Override
    public RoleGroupVO create(RoleGroupVO vo){
	    RoleGroupVO result = super.create(vo);
	    RoleGroupMapping roleGroupRole;
	    for(RoleVO role:vo.getRoles()){
	        roleGroupRole = new RoleGroupMapping();
	        roleGroupRole.setRole_Id(role.getId());
	        roleGroupRole.setRolegroup_Id(result.getId());
	        roleDao.createRoleGroupRole(roleGroupRole);
	    }
	    return result;
	}
}
